package com.example.datasource.aspectj;

import com.example.datasource.annotation.MyDataSource;
import com.example.datasource.config.DynamicDatasourceHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

/**
 * @Description : 切面：切换数据源
 * @Author : Bruce Lee
 * @CreateTime : 2024/4/16
 */

@Aspect
@Component
@Slf4j
public class DynamicDatasourceAspect {

//    @Pointcut("@annotation(com.example.datasource.annotation.MyDataSource)")
//    public void dynamicDatasourcePointcut() {
//    }


    @Around(value = "@annotation(com.example.datasource.annotation.MyDataSource)")
//    @Around("dynamicDatasourcePointcut()")
    public void around(ProceedingJoinPoint joinPoint) throws Throwable {
//        // 获取类上的注解
//        Class<?> targetClass = joinPoint.getTarget().getClass();
//        MyDataSource annotation = targetClass.getAnnotation(MyDataSource.class);

        // 获取方法上的注解
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        MyDataSource annotationMethod = methodSignature.getMethod().getAnnotation(MyDataSource.class);

        if (annotationMethod != null){
            String dataSource = annotationMethod.value();
            // 切换数据源
            DynamicDatasourceHolder.setDataSource(dataSource);
        }

        // 执行方法
        joinPoint.proceed(joinPoint.getArgs());

        // 切换回默认数据源
        DynamicDatasourceHolder.removeDataSource();
    }
}
